/*
 * JHeuristics - The Java Meta-Heuritics Library
 * Copyright (C) 2004-2005, Universidade Federal de Campina Grande. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.jheuristics.ga;

import java.io.Serializable;
import java.util.Iterator;

import org.epanetgrid.otimizacao.simulation.GradienteNaoConvergeOtimizacaoException;
import org.epanetgrid.otimizacao.simulation.SimulacaoNaoConvergeException;
import org.jheuristics.Individual;


/**
 *	Classe que seta o fitness de todos os indiv�duos de uma popula��o
 *
 * @author Marcell Manfrin, marcell@ourgrid.org, Jan 9, 2006
 */
public class SimpleBulkFitnessEvaluator implements BulkFitnessEvaluator, Serializable {
    /**
	 * 
	 */
	private static final long serialVersionUID = -1076433943233256274L;
	private FitnessEvaluator evaluator;

	/**
	 *
	 * @param evaluator Respons�vel por calcular o fitness de um indiv�duo
	 * @throws NullPointerException caso evaluator seja igual a null
	 */
	public SimpleBulkFitnessEvaluator(FitnessEvaluator evaluator) {
		setFitnessEvaluator(evaluator);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jheuristics.ga.BulkFitnessEvaluator#evaluateFitness(org.jheuristics.ga.Population, org.jheuristics.ga.GAStatus, org.jheuristics.ga.GAConfig)
	 */
	public void evaluateFitness(Population population, GAStatus status, GAConfig config) throws GradienteNaoConvergeOtimizacaoException {
		Iterator it = population.iterator();
		while (it.hasNext()) {
			Individual individual = (Individual) it.next();
			if (null == individual.getFitness()) {
				try {
					individual.setFitness(evaluator.evaluateFitness(individual, population, status, config));
				} catch (SimulacaoNaoConvergeException e) {
				}
			}
		}
		
	}

	/**
	 *
	 * @return retorna o objeto respons�vel por calcular o fitness de um indiv�duo
	 */
	public FitnessEvaluator getFitnessEvaluator() {
		return evaluator;
	}

	/**
	 *
	 * @param evaluator Respons�vel por calcular o fitness de um indiv�duo
	 * @throws NullPointerException caso evaluator seja igual a null
	 */
	public void setFitnessEvaluator(FitnessEvaluator evaluator) {
		if (null == evaluator) {
			// TODO: ERROR MSG
		    throw new NullPointerException();
		}
	    this.evaluator = evaluator;
	}

}
